package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_USER_TTL;

public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //TODO 1.获取token
        String token = request.getHeader("authorization");

        //2.如果token为空直接放行（交给第二拦截器专门拦截）
        if (StrUtil.isBlank(token)) {
            return true;
        }

        String userKey = token;
        //TODO 3.根据token在redis中获取user信息
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(userKey);
                                            //注意这里需加上LOGIN_USER_KEY， 前端传回来的值已经被前端去掉了

        //4.判断map是否为空,放行同上
        if(userMap.isEmpty()){
            return true;
        }

        //TODO 5.将map转换为user对象
        UserDTO userDTO = BeanUtil.mapToBean(userMap, UserDTO.class, true, null);

        //6.如果用户存在，保存用户信息到TheardLocal
        UserHolder.saveUser(userDTO);

        //TODO 7.更新redis中user对象的过期时间（此拦截器拦截所有请求，那么redis在任何时候都会正常刷新）
        stringRedisTemplate.expire(userKey, LOGIN_USER_TTL, TimeUnit.MINUTES);

        //8.放行
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //业务处理完成后删除线程中的数据副本
        UserHolder.removeUser();
    }
}
